<template>
	<view class="wrapper">
    <template v-if="tree && tree.length > 0">
      <u--form
          labelPosition="left"
          :model="postForm"
          :rules="rules"
          ref="uForm"
          class="form"
          labelWidth="180rpx"
          labelAlign="right"
          :labelStyle="{'font-size': '24rpx', 'padding-right': '20rpx', 'margin-top': '-3rpx'}"
      >
        <u-form-item
            label="收件人姓名"
            prop="nickname"
        >
          <u--input
              v-model="postForm.nickname"
              border="surround"
              fontSize="24rpx"
              :customStyle="{'height': '30rpx'}"
          ></u--input>
        </u-form-item>
        <u-form-item
            label="收件人电话"
            prop="mobile"
        >
          <u--input
              v-model="postForm.mobile"
              border="surround"
              fontSize="24rpx"
              :customStyle="{'height': '30rpx'}"
          ></u--input>
        </u-form-item>
        <u-form-item
            label="地区"
        >
          <u--input
              v-if="true"
              v-model="postForm.city"
              border="surround"
              fontSize="24rpx"
              :customStyle="{'height': '30rpx', 'background': 'white'}"
              @focus="handleCity"
              :disabled="showPicker"
          ></u--input>
          <u-button
            v-if="false"
            @click="handleCity"
            :text="selectedText.join(', ')"
            :customStyle="{'height': '58rpx', 'border-color': '#dadbde'}"
          ></u-button>
        </u-form-item>
        <u-form-item
            label="详细地址"
            prop="info"
        >
          <u--textarea v-model="postForm.info" placeholder="请输入详细地址" ></u--textarea>
        </u-form-item>
        <u-form-item
            v-if="false"
            label="设为默认地址"
            prop="isDefault"
        >
          <u-switch v-model="postForm.isDefault" size="32" :activeColor="activeColor" inactiveColor="rgb(230, 230, 230)"></u-switch>
        </u-form-item>
        <u-button type="success" class="btn" :color="activeColor" @click="save" :text="buttonText"></u-button>
      </u--form>
      <u-picker
          :show="showPicker"
          itemHeight="80"
          ref="uPicker"
          :columns="columns"
          :closeOnClickOverlay="true"
          @close="closePicker"
          @cancel="closePicker"
          @confirm="confirmPicker"
          keyName="text"
          @change="handlePicker"
      ></u-picker>
    </template>
    <arrow />
  </view>
</template>

<script>
import color from '@/config/color.js'
  import base64 from '../../util/base64'
  import Arrow from '../../components/arrow'
  import Address from '../../api/address'
  const addressModel = new Address()
  import { mapGetters } from 'vuex'

	export default {
    components: {
      Arrow
    },
    computed: {
      ...mapGetters({
        tree: 'Address/tree'
      }),
      buttonText() {
        return this.id && this.id > 0 ? '更新' : '添加'
      }
    },
		data() {
			return {
        activeColor: color.main_color,
			  // 需要用3行数据处理,
        // 页面加载后, 会覆盖下面数据
        columns: [
          ['省', '省2'],
          ['市', '市2'],
          ['区1', '区2'],
        ],
        // 编辑时的默认地址
        defaultIndex: [0, 0, 0],
        showPicker: false,
        selectedText: [],
        selectedValue: [],
			  // -2 下单过来
			  type: 0,
        id: 0,
        postForm: {
			    nickname: ''
        },
        rules: {
          nickname: {
            type: 'string',
            required: true,
            message: '请填写姓名',
            trigger: ['blur', 'change']
          },
          mobile: {
            type: 'string',
            required: true,
            message: '请填写电话',
            trigger: ['blur', 'change']
          },
          info: {
            type: 'string',
            required: true,
            message: '请填写详情地址',
            trigger: ['blur', 'change']
          }
        }
			}
		},
    onReady() {
      // 官方说: 需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
      // 我测试, 好象不需要
      // this.$refs.uForm.setRules(this.rules)
    },
    onLoad(options) {
      if (options.type) {
        this.type = options.type
      }
      if (options.id) {
        this.id = options.id
      }
      // 防止无效
      setTimeout(() => {
        uni.setNavigationBarTitle({
          title: `${this.buttonText}收货地址`
        })
      }, 100)
      this.getTree().then(() => {
        this.init()
      })
		},
		methods: {
      getTree() {
        return new Promise(resolve => {
          if (!this.tree) {
            addressModel.tree().then(response => {
              const { data } = response
              this.$store.dispatch('Address/set_data', data.tree)
              this._handleTree()
            })
          } else {
            this._handleTree()
          }
          resolve()
        })
      },
      _handleTree() {
        // console.log(this.tree)
        this.columns[0] = [...this.tree]
        this.columns[1] = [...this.tree[0].children]
        this.columns[2] = [...this.tree[0].children[0].children]
      },
      init() {
        // 新增
        const info = this.$store.getters['User/info']
        if (info && Object.keys(info).length > 0) {
          this.postForm = Object.assign({}, { ...info, isDefault: true })
        }
        // console.log(this.postForm)
        // bug
        this.postForm.city = ''
        // 编辑
        if (this.id > 0) {
          // 注意, 编辑时的写, 下面是最佳方案
          addressModel.view({ id: this.id }).then(response => {
            const { data } = response
            this.postForm = Object.assign({}, {
              ...data,
              // isDefault: data.is_default === '1',
              isDefault: data.is_default === 1,
              info: data.address
            })
            const a = data.city
            const { province_id, city_id, area_id, province, city, area } = a
            this.selectedValue = [province_id, city_id, area_id]
            this.selectedText = [province, city, area]
            this.postForm.city = this.selectedText.join(', ')
            // 设置编辑时的索引
            this.tree.forEach((x, k1) => {
              // console.log(x.value, province_id, city_id, area_id)
              if (x.value === province_id) {
                // this.columns[1] = [...x.children]
                this.$refs.uPicker.setColumnValues(1, [...x.children])
                this.defaultIndex[0] = k1
                x.children.forEach((y, k2) => {
                  if (y.value === city_id) {
                    // this.columns[2] = [...y.children]
                    this.$refs.uPicker.setColumnValues(2, [...y.children])
                    this.defaultIndex[1] = k2
                    y.children.forEach((z, k3) => {
                      if (z.value === area_id) {
                        this.defaultIndex[2] = k3
                      }
                    })
                  }
                })
              }
            })
            // console.log(this.columns)
            // console.log(this.defaultIndex)
            this.$refs.uPicker.setIndexs(this.defaultIndex)
          })
        }
      },
      closePicker() {
        this.showPicker = false
      },
      // 地区选择确认
      confirmPicker(e) {
        this.showPicker = false
        const { value } = e
        this.selectedText = value.map(x => x.text)
        this.selectedValue = value.map(x => x.value)
        this.postForm.city = this.selectedText.join(', ')
      },
      handlePicker(e) {
        // console.log(this.tree)
        const {
          columnIndex,
          value,
          values,
          index,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.uPicker
        } = e
        // 省
        if (columnIndex === 0) {
          picker.setColumnValues(1, [...this.tree[index].children])
          picker.setColumnValues(2, [...this.tree[index].children[0].children])
        }
        // 市
        if (columnIndex === 1) {
          // console.log(value)
          this.tree.forEach(x => {
            x.children.forEach(y => {
              if (y.value === value[1].value) {
                picker.setColumnValues(2, y.children)
              }
            })
          })
        }
        // 区
        if (columnIndex === 2) {
          // 不用处理
        }
      },
      // 选择地区
      handleCity() {
        this.showPicker = true
        // APP中一定要隐藏
        uni.hideKeyboard()
      },
      save() {
        this.$refs.uForm.validate().then(res => {
          if (this.selectedValue.length === 0) {
            return uni.$u.toast('请选择地区')
          }
          // console.log(this.selectedValue)
          const [province_id, city_id, area_id] = this.selectedValue
          addressModel.edit({
            id: this.id,
            province_id,
            city_id,
            area_id,
            is_default: this.postForm.isDefault ? 1 : 0,
            mobile: this.postForm.mobile,
            nickname: this.postForm.nickname,
            address: this.postForm.info
          }).then(() => {
            uni.$u.toast('操作成功')
            setTimeout(() => {
              if (+this.type === -2) {
                uni.navigateBack()
              } else {
                uni.navigateTo({
                  url: '/sub_service/address/index'
                })
              }
            }, 500)
          })
        }).catch(errors => {
          // uni.$u.toast('校验失败')
        })
      }
		}
	}
</script>

<style lang="scss" scoped>
.wrapper {
  background: $background_color;
  min-height: 100vh;
  //margin: 20rpx;
  border-radius: 10rpx;
  padding: 20rpx;
  .loading {
    padding: 20rpx;
    text-align: center;
    height: 100px;
    line-height: 100px;
    font-size: 24rpx;
    color: #ccc;
  }
  .form {
    padding: 20rpx;
    background: white;
    .btn {
      margin-top: 20px;
    }
  }
}
</style>
